package java6699.lesson14;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.stream.Stream;

/**
 * @program: java_zzx
 * @description:
 * @author: zzx
 * @create: 2022-12-07 18:43
 **/
public class TextServer6699 {
    private int port;

    public TextServer6699() {
        port = 8086;
    }

    public void start() {
        System.out.println(port + "服务已启动");
        try (ServerSocket ss = new ServerSocket(port);
             Socket socket = ss.accept()) {
            session(socket);//开始与客户端通话
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void session(Socket socket) throws IOException {
        //连接成功，在控制台上显示客户端的信息
        String client = socket.getInetAddress().getHostAddress() + ":" + socket.getPort();
        System.out.println(client + "，已接入");
        String path = "data/test6699.txt";
        try(PrintStream printer = new PrintStream(path)) {
            // 包装Socket中的IO字节流
            BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String problem = null;
            while ((problem = reader.readLine()) != null) {
                if ("stop".equalsIgnoreCase(problem)) {
                    break;
                }
                System.out.println(problem);
                printer.println(problem);
            }
        }
    }

    public static void main(String[] args) throws Exception {
        new TextServer6699().start();
    }
}
